package com.zhouyibike.uu.ui.activity.jvbaoandpaiming;

import android.app.Dialog;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.zhouyibike.uu.R;
import com.zhouyibike.uu.config.Config;
import com.zhouyibike.uu.entity.JvBaoInfo;
import com.zhouyibike.uu.entity.JvBaoTypeResult;
import com.zhouyibike.uu.entity.StartRidingResult;
import com.zhouyibike.uu.http.ApiCallback;
import com.zhouyibike.uu.ui.adapter.JBTypeAdapter;
import com.zhouyibike.uu.ui.adapter.PicAdapter;
import com.zhouyibike.uu.ui.base.BaseActivity;
import com.zhouyibike.uu.ui.base.MyApplication;
import com.zhouyibike.uu.utils.Base64Encoder;
import com.zhouyibike.uu.utils.DataSingle;
import com.zhouyibike.uu.utils.FileUtil;
import com.zhouyibike.uu.utils.ImgUtils;
import com.zhouyibike.uu.utils.PhoneUtils;
import com.zhouyibike.uu.utils.TimeUtils;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.util.HashMap;
import java.util.Map;

public class JvBaonotitleActivity extends BaseActivity implements View.OnClickListener {
    private ImageButton mBtnBack;
    private TextView mBtnTitle;
    private GridView gb_alltype, gv_allpic;
    private Button btn_jvbao;
    private EditText et_note, et_plantnum;
    private Dialog jubaodialog, querenjubaodialog;
    private JBTypeAdapter jbTypeAdapter;
    private String jvbaotype;
    private HashMap<Integer, String> piclocation = new HashMap<>();
    private int pressindex = 0;
    private PicAdapter picAdapter;
    private RelativeLayout jubaonopicly, barly;
    private String bikenum;
    private TextView querenjubao_queding, querenjubao_quxiao;
    private int time = 5;
    private Handler timehandler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message message) {
            if (time == 1) {
                querenjubao_queding.setEnabled(true);
                querenjubao_queding.setText("确定");
                time = 5;
                timehandler.removeMessages(0);
            } else {
                time--;
                querenjubao_queding.setText("确定(" + time + "S)");
                querenjubao_queding.setEnabled(false);
                timehandler.sendEmptyMessageDelayed(0, 1000);
            }
            return false;
        }
    });

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_jv_bao2);
        bikenum = getIntent().getStringExtra("bikenum");
        initView();
//        getMsg();
        initPic();
        setjubaoDialog();
        setquerenjubaoDialog();
        gb_alltype.setVisibility(View.GONE);
    }

    private void initView() {
        jubaonopicly = (RelativeLayout) findViewById(R.id.jubaonopicly);
        mBtnBack = (ImageButton) findViewById(R.id.bar_btn_back);
        mBtnTitle = (TextView) findViewById(R.id.bar_text_title);
        mBtnTitle.setText("联系我们");
        mBtnBack.setOnClickListener(this);
        barly = (RelativeLayout) findViewById(R.id.barly);
        if (barly != null) {
            barly.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    setResult(132);//退出冻结界面
                    finish();
                }
            });
        }
        et_note = (EditText) findViewById(R.id.et_jvbao_note);
        et_plantnum = (EditText) findViewById(R.id.et_jvbao_plantnum);
        et_plantnum.setText(bikenum);
        btn_jvbao = (Button) findViewById(R.id.btn_jvbao_supply);
        btn_jvbao.setOnClickListener(this);
        gb_alltype = (GridView) findViewById(R.id.gb_jvbao_alltype);
        gv_allpic = (GridView) findViewById(R.id.gb_jvbao_allpic);
        gv_allpic.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                pressindex = position;
                showPopupWindow();
            }
        });
        jubaonopicly.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                pressindex = 0;
                showPopupWindow();
            }
        });
    }

    private String imagePath;

    //打开相机
    public void byCamera() {
        String savePath = "";
        String storageState = Environment.getExternalStorageState();
        if (storageState.equals(Environment.MEDIA_MOUNTED)) {
            savePath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/camera/";
            File savedir = new File(savePath);
            if (!savedir.exists()) {
                savedir.mkdirs();
            }
        }

        // 没有挂载SD卡，无法保存文件
        if (savePath == null || "".equals(savePath)) {
            System.out.println("无法保存照片，请检查SD卡是否挂载");
            return;
        }

        String timeStamp = TimeUtils.getCurrentTimeInString();
        //照片命名
        String fileName = timeStamp + ".jpg";
        File out = new File(savePath, fileName);
//        Uri uri = Uri.fromFile(out);
        //该照片的绝对路径
        imagePath = savePath + fileName;
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        ContentValues contentValues = new ContentValues(1);
        contentValues.put(MediaStore.Images.Media.DATA, out.getAbsolutePath());
        Uri uri = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, contentValues);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
        startActivityForResult(intent, 0x008);
    }

    //打开相册
    private void openAlbum() {
        Intent intent = new Intent("android.intent.action.GET_CONTENT");
        intent.setType("image/*");
        startActivityForResult(intent, 0x006); // 打开相册
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 8 && resultCode == RESULT_OK) {
            if (imagePath != null) {
                jubaonopicly.setVisibility(View.GONE);
                gv_allpic.setVisibility(View.VISIBLE);
                piclocation.put(pressindex, imagePath);
                selist();
            }
        }
        if (requestCode == 6 && resultCode == RESULT_OK) {
            piclocation.put(pressindex, FileUtil.getFilePath(this, data.getData()));
            selist();
        }

    }

    public void backgroundAlpha(float bgAlpha) {
        WindowManager.LayoutParams lp = getWindow().getAttributes();
        lp.alpha = bgAlpha; //0.0-1.0
        getWindow().setAttributes(lp);
    }

    PopupWindow popupWindow;

    private void showPopupWindow() {
        View view = getLayoutInflater().inflate(R.layout.select_tackphoto_type, null);

        popupWindow = new PopupWindow(view, WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.WRAP_CONTENT, true);
        popupWindow.setBackgroundDrawable(new BitmapDrawable());
        popupWindow.setFocusable(true);

        popupWindow.setAnimationStyle(R.style.mypopwindow_anim_style);
        backgroundAlpha(0.5f);
        popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                backgroundAlpha(1f);
            }
        });
        popupWindow.showAtLocation(this.findViewById(R.id.bar_btn_back),
                Gravity.BOTTOM, 0, PhoneUtils.getBottomStatusHeight(this));
        TextView btn_camera = (TextView) view.findViewById(R.id.btn_take_photo);
        TextView btn_takelocation = (TextView) view.findViewById(R.id.btn_pick_photo);
        btn_takelocation.setVisibility(View.GONE);
        TextView btn_cancle = (TextView) view.findViewById(R.id.btn_cancel);
        btn_camera.setOnClickListener(this);
        btn_takelocation.setOnClickListener(this);
        btn_cancle.setOnClickListener(this);
    }

    private void getMsg() {
        Map<String, String> params = new HashMap<>();
        params.put("token", preferences.getString("token", ""));
        showProgressDialog();
        addSubscription(apiStores.GetRepairList(params),
                new ApiCallback<JvBaoTypeResult>() {

                    @Override
                    public void onSuccess(JvBaoTypeResult model) {
                        if (model.getStatus() == Config.SUCCESSCODE) {
                            initType(model);
                        } else {
                            toastShow(model.getMessage());
                        }
                    }

                    @Override
                    public void onFailure(String msg) {
                        toastShow(msg);

                    }

                    @Override
                    public void onFinish() {
                        dismissProgressDialog();
                    }
                });
    }

    private void initType(JvBaoTypeResult model) {
        jbTypeAdapter = new JBTypeAdapter(this, model.getData());
        gb_alltype.setAdapter(jbTypeAdapter);
        gb_alltype.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                jbTypeAdapter.setpreid(view.getTag().toString());
                jvbaotype = view.getTag().toString();
                btn_jvbao.setEnabled(true);
            }
        });
    }

    private void selist() {
        picAdapter.setlist(piclocation);
    }

    private void initPic() {
        picAdapter = new PicAdapter(this, piclocation);
        gv_allpic.setAdapter(picAdapter);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.bar_btn_back:
                setResult(132);//退出冻结界面
                finish();
                break;
            case R.id.btn_take_photo:
                popupWindow.dismiss();
                byCamera();
                break;
            case R.id.btn_pick_photo:
                popupWindow.dismiss();
                openAlbum();
                break;
            case R.id.btn_cancel:
                popupWindow.dismiss();
                break;
            case R.id.btn_jvbao_supply:
                setbase64();
                if (images == null) {
                    toastShow("请拍摄单车环境");
                } else {
                    querenjubaodialog.show();
                    querenjubao_queding.setText("确定(5S)");
                    querenjubao_queding.setEnabled(false);
                    timehandler.sendEmptyMessageDelayed(0, 1000);
                    //jvbao();
                }
                break;
        }
    }

    String images1;
    String[] images;

    private void setbase64() {
        for (int i = 0; i < piclocation.size(); i++) {
            switch (i) {
                case 0:
                    images1 = bitmaptoString(ImgUtils.getSmallBitmap(piclocation.get(i)));
                    break;
                case 2:
                    images1 = images1 + "lyl123" + bitmaptoString(ImgUtils.getSmallBitmap(piclocation.get(i)));
                    break;
                case 3:
                    images1 = images1 + "lyl123" + bitmaptoString(ImgUtils.getSmallBitmap(piclocation.get(i)));
                    break;
                case 4:
                    images1 = images1 + "lyl123" + bitmaptoString(ImgUtils.getSmallBitmap(piclocation.get(i)));
                    break;
                case 5:
                    images1 = images1 + "lyl123" + bitmaptoString(ImgUtils.getSmallBitmap(piclocation.get(i)));
                    break;
                case 1:
                    images1 = images1 + "lyl123" + bitmaptoString(ImgUtils.getSmallBitmap(piclocation.get(i)));
                    break;
            }
        }
        if (images1 != null) {
            images = images1.split("lyl123");
        } else {
            images = null;
        }

    }

    public String bitmaptoString(Bitmap bitmap) {
        // 将Bitmap转换成字符串

        String string = "";

        ByteArrayOutputStream bStream = new ByteArrayOutputStream();

        bitmap.compress(Bitmap.CompressFormat.JPEG, 30, bStream);

        byte[] bytes = bStream.toByteArray();
        Base64Encoder base = new Base64Encoder();
        string = base.encode(bytes); //
        return string;
    }

    private void jvbao() {

        JvBaoInfo jvBaoInfo = new JvBaoInfo();
        jvBaoInfo.setToken(preferences.getString("token", ""));
        JvBaoInfo.DataBean jd = new JvBaoInfo.DataBean();
        // jd.setNoteType("关锁后未结算");
        jd.setLatitude(MyApplication.getInstances().getLat());
        jd.setLongitude(MyApplication.getInstances().getLng());
        jd.setFileName("a.jpg");
        jd.setNotes(et_note.getText().toString());
        jd.setPlateNumber(et_plantnum.getText().toString());
        jd.setImages(images);
        jvBaoInfo.setModel(jd);
//        String json=new Gson().toJson(jvBaoInfo);
//        Log.e( "jvbao: ", json);
        showProgressDialog();
        btn_jvbao.setEnabled(false);
        addSubscription(apiStores.ReportCloseTocker(jvBaoInfo),
                new ApiCallback<StartRidingResult>() {

                    @Override
                    public void onSuccess(StartRidingResult model) {
                        if (model.getStatus() == 200) {
                            setResult(123);//刷新主界面状态 冻结
                            jubaodialog.show();
                        } else {
                            toastShow(model.getMessage());
                        }

                    }

                    @Override
                    public void onFailure(String msg) {
                        toastShow(msg);

                    }

                    @Override
                    public void onFinish() {
                        btn_jvbao.setEnabled(true);
                        dismissProgressDialog();
                    }
                });

    }

    //举报成功对话框
    private void setjubaoDialog() {
        TextView jubaookknow;
        LayoutInflater inflater = LayoutInflater.from(JvBaonotitleActivity.this);
        final View headview = inflater.inflate(R.layout.jubao_ok_dialog, null, false);
        jubaookknow = headview.findViewById(R.id.jubaookknow);
        jubaodialog = new Dialog(this, R.style.Dialog_Fullscreen);
        jubaodialog.setContentView(headview, new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.MATCH_PARENT,
                LinearLayout.LayoutParams.WRAP_CONTENT));
        jubaodialog.setCanceledOnTouchOutside(false);
        Window dialogWindow = jubaodialog.getWindow();
        dialogWindow.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_NOTHING);
//        adjustPan|stateHidden
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        dialogWindow.setGravity(Gravity.CENTER);
//                lp.x = 100; // 新位置X坐标
//          lp.y = 100; // 新位置Y坐标
        lp.width = (int) (DataSingle.getInstance().PhoneW * 0.75); // 宽度
        lp.height = (int) (DataSingle.getInstance().PhoneW * 0.75);
//         lp.alpha = 0.7f; // 透明度
        // 当Window的Attributes改变时系统会调用此函数,可以直接调用以应用上面对窗口参数的更改,也可以用setAttributes
        // dialog.onWindowAttributesChanged(lp);
        dialogWindow.setWindowAnimations(R.style.mypopwindow_anim_style3);  //添加动画
        dialogWindow.setAttributes(lp);
        jubaookknow.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                jubaodialog.dismiss();
                JvBaonotitleActivity.this.finish();
            }
        });
        DialogInterface.OnKeyListener keylistener = new DialogInterface.OnKeyListener() {
            public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
                    return true;
                } else {
                    return false;
                }
            }
        };
        jubaodialog.setOnKeyListener(keylistener);
    }

    //确认举报对话框
    private void setquerenjubaoDialog() {
        LayoutInflater inflater = LayoutInflater.from(JvBaonotitleActivity.this);
        final View headview = inflater.inflate(R.layout.querenjubao_ok_dialog, null, false);
        querenjubaodialog = new Dialog(this, R.style.Dialog_Fullscreen);
        querenjubao_queding = headview.findViewById(R.id.querenjubao1);
        querenjubao_quxiao = headview.findViewById(R.id.quxiaojubao1);
        querenjubaodialog.setContentView(headview, new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.MATCH_PARENT,
                LinearLayout.LayoutParams.MATCH_PARENT));
        querenjubaodialog.setCanceledOnTouchOutside(false);
        Window dialogWindow = querenjubaodialog.getWindow();
        dialogWindow.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_NOTHING);
//        adjustPan|stateHidden
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        dialogWindow.setGravity(Gravity.CENTER);
//                lp.x = 100; // 新位置X坐标
//          lp.y = 100; // 新位置Y坐标
        lp.width = (int) (DataSingle.getInstance().PhoneW); // 宽度
        lp.height = (int) (DataSingle.getInstance().PhoneH);
//         lp.alpha = 0.7f; // 透明度
        // 当Window的Attributes改变时系统会调用此函数,可以直接调用以应用上面对窗口参数的更改,也可以用setAttributes
        // dialog.onWindowAttributesChanged(lp);
        //  dialogWindow.setWindowAnimations(R.style.mypopwindow_anim_style3);  //添加动画
        dialogWindow.setAttributes(lp);
        DialogInterface.OnKeyListener keylistener = new DialogInterface.OnKeyListener() {
            public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
                    return true;
                } else {
                    return false;
                }
            }
        };
        querenjubao_quxiao.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                querenjubaodialog.dismiss();
                timehandler.removeMessages(0);
                time = 5;
            }
        });
        querenjubao_queding.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                querenjubaodialog.dismiss();
                jvbao();
            }
        });
        querenjubaodialog.setOnKeyListener(keylistener);
    }

    public boolean isShouldHideInput(View v, MotionEvent event) {
        if (v != null && (v instanceof EditText)) {
            int[] leftTop = {0, 0};
            //获取输入框当前的location位置
            v.getLocationInWindow(leftTop);
            int left = leftTop[0];
            int top = leftTop[1];
            int bottom = top + v.getHeight();
            int right = left + v.getWidth();
            if (event.getX() > left && event.getX() < right
                    && event.getY() > top && event.getY() < bottom) {
                // 点击的是输入框区域，保留点击EditText的事件
                return false;
            } else {
                return true;
            }
        }
        return false;
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            View v = getCurrentFocus();
            if (isShouldHideInput(v, ev)) {

                InputMethodManager imm = (InputMethodManager) getSystemService(JvBaoActivity.INPUT_METHOD_SERVICE);
                if (imm != null) {
                    imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
                }
            }
            return super.dispatchTouchEvent(ev);
        }
        // 必不可少，否则所有的组件都不会有TouchEvent了
        if (getWindow().superDispatchTouchEvent(ev)) {
            return true;
        }
        return onTouchEvent(ev);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    @Override
    public void onBackPressed() {
        setResult(132);//退出冻结界面
        super.onBackPressed();

    }
}
